package com.then.basic.socket.core;

import java.util.concurrent.atomic.AtomicBoolean;

import org.greenrobot.eventbus.EventBus;

import com.then.basic.socket.SafeHandler;
import com.then.basic.socket.core.error.CommonError;

import android.os.Looper;
import android.util.Log;

public class CheckOnlineTask {
    private volatile long preTime;
    private volatile AtomicBoolean runningFlag = new AtomicBoolean();
    /**
     * 判定超时的标准
     **/
    private int timeOutInterval = 10000; // 10秒即判定为超时
    private int type;
    /**
     * 检测超时次数，
     */
    private int offLineTime = 0;
    private int waitInterval = 5000; // 每次检测间隔5秒

    private static final String TAG = "ChkOnlineTask";

    private SafeHandler safeHandler = new SafeHandler(Looper.getMainLooper(), SafeHandler.EMPTY_MESSAGE_PROCESSOR);

    private Runnable checkOnlineRunnable = new Runnable() {
        @Override
        public void run() {
            if (!runningFlag.get()) {
                return;
            }

            long nowTime = System.currentTimeMillis();
            if ((nowTime - preTime) > timeOutInterval) {
                // 已经超过规定时间没有和服务器通信，表示已经掉线
                offLineTime++;
                Log.w(TAG, "send offline message! server type:" + type + " time:" + (nowTime - preTime) * 0.001f
                        + "s count:" + offLineTime);
                EventBus.getDefault().post(new CommonError.NetworkErrorInfo(
                        CommonError.NetworkErrorInfo.ErrorType.SendPackageFail, type, offLineTime));
            } else {
                offLineTime = 0;
            }

            if (runningFlag.get() && offLineTime < 5) { // 避免意外情况没能停止下来
                safeHandler.postDelayed(this, waitInterval); // 计划下次再检查
            }
        }
    };

    /**
     * 初始化掉线检测线程
     *
     * @param type 1:资源服务器 2:游戏服务器  3:其他情况掉线
     */
    public CheckOnlineTask(int type) {
        this.type = type;
        if (type == 1) {
            timeOutInterval = 60000;
        } else if (type == 2) {
            timeOutInterval = 20000;
        }
    }

    public synchronized void start() {
        stop();
        Log.d(TAG, "type:" + type + " start!");
        offLineTime = 0;
        runningFlag.set(true);
        preTime = System.currentTimeMillis();
        safeHandler.postDelayed(checkOnlineRunnable, waitInterval);
    }

    public void setUpdateTime(long time) {
        preTime = time;
    }

    public void stop() {
        if (runningFlag.get()) {
            runningFlag.set(false);
            Log.i(TAG, "type:" + type + " stop!");
        }
        safeHandler.removeCallbacks(checkOnlineRunnable);
    }
}